/*********************
    务必设置根目录 
*********************/
let path = 'http://localhost/%e5%b0%8fA%e4%ba%8c%e8%bd%ae%e8%80%83%e6%a0%b8%e4%bb%bb%e5%8a%a1/littleASecondExam/project/';
let isSending = false, /* 防止多次请求 */
    uid = sessionStorage.getItem('id'),
    layer,
    viewport = document.documentElement,
    timer = null;
function request(url, method, data, format = 'application/json') {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    if(isSending == true) {
      xhr.abort();
    }
    isSending = true;

    xhr.responseType = 'json';
    xhr.open(method, url, true);
    /* 有请求头 */
    if(format != 'none') {
      xhr.setRequestHeader("Content-type", format);
    }
    method == 'POST' ? xhr.send(data) : xhr.send();
    xhr.onload = function(){
      isSending = false;
      if(this.status == 200){
        resolve(this.response);
      }
    }
    xhr.ontimeout = function() {
      reject('请求超时，请刷新重试！');
    }
    xhr.onerror = function() {
      reject('加载失败');
      alert('加载失败')
    }
  });
}
function setCookie(name,value,exdays) {
  let date = new Date();
  date.setTime(date.getTime() + (exdays*24*60*60*1000));
  let expires = "expires=" + date.toGMTString();
  document.cookie = name + "=" + value + "; " + expires;
}
function getCookie(name) {
  if (document.cookie.length > 0) {
    let start = document.cookie.indexOf(name + "=");
    if (start != -1) {
      start = start + name.length + 1;
      let end = document.cookie.indexOf(";", start);
      if (end == -1) end = document.cookie.length;
      return decodeURI(document.cookie.substring(start, end));
    }
  }
  return null;
}
function loadHeadImg() {
  /* 加载头像 */
  let profileIcon = document.getElementsByClassName('profile')[0],
  headImg = sessionStorage.getItem('headImg');
  if(headImg == 'null') {
    headImg = path + 'img/user-icon.png';
  }else {
    headImg = 'http://'+ headImg;
  }
  profileIcon.innerHTML = `<a href="${path}profile/index.html"><img src="${headImg}" alt="头像"/></a>`
}
function resetPassword() {
  const resetData = {
    email: forgetPass.email.value,
    newPassword: forgetPass.password.value,
    code: forgetPass.code.value
  }
  let btn = document.getElementById('reset-password');
  btn.setAttribute('disabled','disabled');
  let passwordConfirm = forgetPass.passwordConfirm.value;
  let checkRes = checkFormat(resetData.email, undefined, resetData.newPassword, passwordConfirm);
  if(checkRes != false) {
    request('http://175.178.51.126:8091/smallA/rememberPwd', 'POST', JSON.stringify(resetData))
    .then(value => {
      if(value.code == 200) {
        alert('修改成功！');
        location.reload();
      }else {
        alert('修改失败！' + value.msg);
        btn.removeAttribute('disabled');
      }
    })
    .catch(error => {
      console.log(error);
      btn.removeAttribute('disabled');
    })
  }else {
    btn.removeAttribute('disabled');
  }
}
function getCode() {
  const codeData = {
    email: forgetPass.email.value
  }
  btn = document.getElementById('get-code');
  btn.setAttribute('disabled','disabled');
  btn.className = 'primary full disabled';
  let checkRes = checkFormat(codeData.email);
  if(checkRes != false){
    request('http://175.178.51.126:8091/smallA/getCode', 'POST', JSON.stringify(codeData))
    .then(value => {
      if(value.code == 200) {
        alert('获取成功！请查收邮箱！');
      }else{
        alert("获取失败！" + value.msg);
        btn.removeAttribute('disabled');
        btn.className = 'primary full';
      }
    })
    .catch(error => {
      console.log(error);
      btn.removeAttribute('disabled');
      btn.className = 'primary full';
    })
  }else {
    btn.removeAttribute('disabled');
    btn.className = 'primary full';
  }
}
function isLogin() {
  console.log(getCookie('id'))
  if(getCookie('id') != null) {
    sessionStorage.setItem('id', getCookie('id'))
    sessionStorage.setItem('username', getCookie('username'))
    sessionStorage.setItem('email', getCookie('email'))
    sessionStorage.setItem('age', getCookie('age'))
    sessionStorage.setItem('headImg', getCookie('headImg'))
    sessionStorage.setItem('phone', getCookie('phone'))
    sessionStorage.setItem('sex', getCookie('sex'))
  }
  let id = sessionStorage.getItem('id');
  console.log(id);
  if(id == null) {
    alert('登录已过期，请重新登录！');
      location.href = path + 'authentication.html';
  }
}
function logOut() {
  sessionStorage.removeItem('id');
  sessionStorage.removeItem('username');
  sessionStorage.removeItem('email');
  sessionStorage.removeItem('headImg');
  sessionStorage.removeItem('phone');
  sessionStorage.removeItem('sex');
  sessionStorage.removeItem('age');
  let cookiePath = location.pathname.substring(0,location.pathname.length - 19);
  document.cookie = "id=''; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + cookiePath;
  document.cookie = "username=''; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + cookiePath;
  document.cookie = "email=''; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + cookiePath;
  document.cookie = "headImg=''; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + cookiePath;
  document.cookie = "phone=''; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + cookiePath;
  document.cookie = "sex=''; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + cookiePath;
  document.cookie = "age=''; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=" + cookiePath;
  location.href = '../authentication.html';
}
function openImg(div){
  let layerDiv = document.createElement('div');
  layerDiv.setAttribute('class','layer img');
  layerDiv.innerHTML += `
    <img src="${div.src}" alt="图片" class="open-img"/>
  `
  document.body.appendChild(layerDiv);
  layerDiv.addEventListener('click', event => {
    if(event.target.className == 'layer img') {
      let layer = document.getElementsByClassName('layer img')[0];
      document.body.removeChild(layer);
    }
  })
}
function confirmBox(operation, params, title, content, func) {
  /* 
    operation: open或者close
    params:如果点确定之后执行函数的参数
    title: 提示框标题
    content: 提示框内容
    func: 点确定之后执行的函数名
  */
  console.log(operation)
  if(operation == 'open') {
   let layerDiv = document.createElement('div');
   layerDiv.className = 'layer';
   layerDiv.innerHTML = `
   <div class="confirm-box">
        <h2>${title}</h2>
        <p>${content}</p>
        <div class="selector">
          <button type="button" name="yes" class="primary large">确认</button>
          <button type="button" name="no" class="primary large">取消</button>
        </div>
      </div>
   `
   document.body.appendChild(layerDiv);
   layer = document.getElementsByClassName('layer')[0];
  }else if(operation == 'close') {
    layer = document.getElementsByClassName('layer')[0];
    layer.remove();
  }
  layer.addEventListener('click', event => {
    if(event.target.name == 'yes') {
      func(params)
    }else if(event.target.name == 'no'){
      confirmBox('close')
    }
  })
}
function toText(content) {
  content = content.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  return content;
}
function isVisible(element) {
  let rect = element.getBoundingClientRect();
  // 用户不管是从上向下、从下向上、从左向右、从右向左滑动，都可以判断当前元素是否在可视区域
  return rect.top < viewport.clientHeight && rect.bottom > 0 && rect.left < viewport.clientWidth && rect.right > 0;
}
function lazyLoadImg(img) {
  for(let i=0;i<img.length;i++) {
    if (isVisible(img[i])) {
      img[i].src = 'http://' + img[i].getAttribute('data-src');
    }
  }
}
/* 防抖函数 */
function debounce(func, wait) {
  let timeout = null;
  return function() {
    if(timeout !== null) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(func, wait);  
  }
}